<?php

declare( strict_types = 1 );

namespace App\Common\Model\Base\DataUnit;

use App\Common as com;
use App\Common\Model as nameModel;
use App\Common\Model\Base as nameBase;
use App\Common\Model\Base\DataUnit as nameDataUnit;

class JoinModel extends nameDataUnit\Base {

	/**
	 * @var nameModel\Base\DataUnit\JoinModel\Item[]
	 */
	protected array $_joinModelPool = [];

	public function eventDatasBefore(  ) {
		foreach( $this->_joinModelPool as $joinValue ){
			$joinValue->eventDataBeforeOfJoin();
		}
	}

	public function eventDatasLater( &$dataQuote ) {
		foreach( $this->_joinModelPool as $joinValue ){
			$joinValue->eventDataLaterOfJoin( $dataQuote );
		}
	}

	/**
	 * 创建item（不存在则创建）
	 * @param string $itemName item名
	 * @param \Closure $newCallBack 创建的函数
	 * @param \Closure|null $newLaterCallBack 创建后的回调 $fn( $newItem )
	 * @return mixed 返回item(JoinModel\Item)
	 */
	protected function getItemOrNew( string $itemName, \Closure $newCallBack, ?\Closure $newLaterCallBack = null ){
		if( ! isset( $this->_joinModelPool[ $itemName ] ) ){
			$this->_joinModelPool[ $itemName ] = call_user_func( $newCallBack );
			//
			$this->initJoinDataUnitParam( $this->_joinModelPool[ $itemName ] );
			//
			if( is_callable( $newLaterCallBack ) ){
				$newLaterCallBack( $this->_joinModelPool[ $itemName ] );
			}
		}
		//
		return $this->_joinModelPool[ $itemName ];
	}

	/**
	 * 初始化join参数
	 * @param com\Model\Base\DataUnit $dataUnit
	 * @return nameModel\Base\DataUnit
	 */
	protected function initJoinDataUnitParam( nameModel\Base\DataUnit $dataUnit ):nameModel\Base\DataUnit {
		if( $dataUnit->goOption()->getIsCleanIncompleteData() === null && $this->getDataUnit()->goOption()->getIsCleanIncompleteData() ){
			$dataUnit->goOption()->setIsCleanIncompleteData( true );
		}
		//
		return $dataUnit;
	}

}
